﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.SessionState;
using DataBaseHelper;

/// <summary>
/// SinglePlay 单人模式服务器控制流程
/// </summary>
public static class SinglePlay
{
    public class Result
    {
        public bool bOk = false;
        public string sMsg = null;
        public string sDebug = null;
        public object data = null;
    }

    public static string GetMapsSQL =
@"
SELECT TOP 30 *
FROM
M_Maps
ORDER BY NEWID()
";

    public static JavaScriptSerializer JSON = new JavaScriptSerializer();

    public static string GetMap(HttpRequest Request, HttpSessionState Session)
    {
        Result res = new Result();
        Queue<Map> maps = Session["maps"] as Queue<Map>;
        if (maps == null || maps.Count < 1)
        {
            IDBS dbs = new SqlDBS();
            dbs.Prepare(GetMapsSQL);
            DataSet ds;
            if (dbs.ExecuteQuery(out ds))
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    maps = new Queue<Map>();
                    foreach (DataRow r in ds.Tables[0].Rows)
                    {
                        maps.Enqueue(new Map(r));
                    }
                    res.bOk = true;
                    res.data = maps.Dequeue();
                    Session["maps"] = maps;
                }
                else
                {
                    Exception ex = dbs.LastError;
                    res.bOk = false;
                    res.sMsg = "服务器内部错误。";
                    res.sDebug = "No data";
                }
            }
            else
            {
                Exception ex = dbs.LastError;
                res.bOk = false;
                res.sMsg = "服务器内部错误。";
                res.sDebug = ex.ToString();
            }
        }
        else
        {
            res.bOk = true;
            res.data = maps.Dequeue();
        }
        return JSON.Serialize(res);
    }
}

[Serializable]
public class Map
{
    public int ID { get; private set; }
    public int Size { get; private set; }
    public int Dot { get; private set; }
    public string Matrix { get; private set; }
    public DateTime PublishTime { get; private set; }
    public int MapLevel { get; private set; }

    public Map(DataRow dr)
    {
        ID = dr["ID"] as int? ?? -1;
        Size = dr["Size"] as byte? ?? -1;
        Dot = dr["Dot"] as byte? ?? -1;
        MapLevel = dr["MapLevel"] as byte? ?? -1;
        Matrix = dr["Map"] as string;
        PublishTime = dr["PublishTime"] as DateTime? ?? DateTime.Now;
    }
}